<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽会员健身报告查询</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>会员健身报告查询</h2>
    <div class="form-row" >
        <div style="color:rgb(186, 181, 143);width:100px;font-weight: bold;font-size:14px;" >会员ID及姓名 </div >
        <input id='cusName' style="width:100px;" oninput="handleCusNameInput()" onclick="handleCusNameInput()">    
        <div id="cusNameList" style="display:none;"></div>
    </div>   
    
    <div id="selectInsBox" class="form-row" style="flex-flow:row;margin-top:15px;">
        <div style="color:rgb(186, 181, 143);width:100px;font-weight: bold; font-size:14px;">选择签名教练 </div>
        <select id="insSel"></select>
    </div>


    <!-- <div style="margin-left:2px;margin-top:30px;"><button id='submit' onclick="showReport();">查询</button></div> -->
    <hr>

    <div id="reportBox">
        <div id='title' ></div>
        <div id="reportDate"></div>
        <div id='cusNameReport'></div>

        <div id="trainData"></div>
        <div id="errInfoTrain"></div>
        <div id="trainCalendar" style="width:100%;"></div>

        

        <div id="bodyData" class="chart-wrapper" style="flex-flow:column;width:100%;" >
            <div id="bodyTitle" ></div>
            <div id="bfr" class="chart-wrapper" style="width:100%;height:200px;"></div>
            <hr style="width:96%;border:none;height:1px;background-color:rgb(245, 225, 212)">
            <div id="bmi" class="chart-wrapper" style="width:100%;height:200px;"></div>
            <hr style="width:96%;border:none;height:1px;background-color:rgb(245, 225, 212)">
            <div id="radarBox" class="chart-wrapper" style="width:100%;height:400px;"></div>
        
            <div id="changeTitle"></div>
            <div id="wtChange" class="chart-wrapper" style="width:100%;height:400px;border-radius: 14px;"></div>
            <br>
            <div id="chestChange" class="chart-wrapper" style="width:100%;height:400px;border-radius: 14px;"></div>
            <br>
            <div id="waistChange" class="chart-wrapper" style="width:100%;height:400px;border-radius: 14px;"></div>
            <br>
            <div id="hipChange" class="chart-wrapper" style="width:100%;height:400px;border-radius: 14px;"></div>
            <br>
            <div id="legChange" class="chart-wrapper" style="width:100%;height:400px;border-radius: 14px;"></div>
            <br>
            <div id="armChange" class="chart-wrapper" style="width:100%;height:400px;border-radius: 14px;"></div>
            

            
        </div> 
        <div id="errInfo"></div>

        <div id="insSig"></div>
    </div>


  

    <script src="../static/js/common.js"></script>
    <script src="../static/js/echarts.min.js"></script>
    
    <script>
        let allTrialList;
        let insName;
        let insId;
        let insRole;
        let cusList;
        let insNicknameDic;
        let insSigTxt;
        let pageTxtLib;
        let myChart;

        document.addEventListener('DOMContentLoaded',function(){
            // loginCheck();

            const cusNameList=document.getElementById('cusNameList');
            document.addEventListener("click",function(){
                cusNameList.style.display='none';
            });

            fetch('./get_page_txts')
            .then(response=>response.json())
            .then(data=>{
                // console.log('get txt lib:',data);
                pageTxtLib=data;
            })
            .catch(error=>{
                console.log('获取页面描述文本错误',error);
            })

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                //console.log('cus list:',data);
                cusList=data;
                  })
                .catch(error => console.error('Error:', error));

            // fetch('/get_trial_list')
            // .then(response=>response.json())
            // .then(data=>{
            //     // console.log(data)
            //     allTrialList=data;
            //     // generateTrialCusList(data);
                
            // })
            // .catch(error=>{
            //     console.log('获取体验课列表错误：',error)
            // });

            fetch('/get_ins_nickname', {
                method: 'GET',
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                
                insNicknameDic=data['ins_nickname_list'];
                //console.log('ins nicknames:',insNicknameDic);

                fetch('/get_ins_list', {
                    method: 'GET',
                    })
                    .then(response => response.json())
                    .then(data => {
                    //将data赋值给块变量cus_list，供后面的handleInput使用
                        console.log('ins list:',data);
                        showInsList(data['ins_list']);
                        generateInsNickName();
                    })
                    .catch(error => console.error('Error:', error));
                })
                .catch(error => console.error('Error:', error));

            // fetch('/get_ins_list', {
            //     method: 'GET',
            //     })
            //     .then(response => response.json())
            //     .then(data => {
            // //将data赋值给块变量cus_list，供后面的handleInput使用
            //     console.log('ins list:',data);
            //     showInsList(data['ins_list']);
            //     generateInsNickName();
            //      })
            //     .catch(error => console.error('Error:', error));

            

            
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            // console.log(insName)
            //教练角色不显示选择框，签名为教练本人，管理员角色显示教练选择框。
            const selectInsBox=document.getElementById('selectInsBox');
            selectInsBox.style.display='none';       

            // console.log('ins sig:',insSigTxt)            

            const bodyData=document.getElementById('bodyData');
            bodyData.style.display='none';

            const insSig=document.getElementById('insSig');
            insSig.innerHTML='';


        });

        function generateInsNickName(){
            if(insRole==='ins'){
                selectInsBox.style.display='none';
                insSigTxt=insNicknameDic[insId+insName];
            }else{
                selectInsBox.style.display='flex';
                insSigTxt=insNicknameDic[document.getElementById('insSel').value];
            }
            //console.log('ins nick name:',insSigTxt);
        }

        function showInsList(insList){
            const insSelect=document.getElementById('insSel');            
            insList.forEach(item=>{
                const opt=document.createElement('option');
                opt.value=item;
                opt.textContent=item.slice(8,);
                insSelect.appendChild(opt);
            });
            insSelect.addEventListener('change',()=>{generateInsNickName();showReport();});
        }

        function yRangeRes(arr){
            const numbers= arr.map(parseFloat);
            const min = Math.min(...numbers)
            const max = Math.max(...numbers)

            let roundedMin=Math.floor(min/10)*10
            let roundedMax=Math.ceil(max/10)*10


            if(roundedMin%10===0 || roundedMin%10===1 || roundedMin%10===2 ){
                roundedMin=roundedMin-5;
            }

            if(roundedMax%10===9 || roundedMax%10===0 ){
                roundedMax=roundedMax+5;
            }            

            const res= [roundedMin,roundedMax]  
    

            return  res

        }

        function showReport(){            
            const trainCalendar=document.getElementById('trainCalendar');
            trainCalendar.innerHTML='';
            const reportBox=document.getElementById('reportBox');
            reportBox.style.display='flex';
            const title=document.getElementById('title');
            const nameReport=document.getElementById('cusNameReport');
            nameReport.innerHTML='';            
            title.innerHTML=`<h1 style='color:#d9c7b0;text-decoration:underline;text-underline-offset:6px;'>鹿鹿泽会员健身报告</h1>`
        
            //训练报告
            getCusTrainData();

            //训练日历
            getCusTrainCalendar();

            //身体报告
            getCusReportBodyData();

            //教练昵称签名
            showInsSig();
        }

        function  getCusTrainCalendar(){     
            const interval=30;   
            try{
                myChart.dispose();
            }catch(error){
                
            }

            let startDate;
            let endDate;
            startDate = new Date();
            startDate.setDate(startDate.getDate() - interval+1);
            endDate = new Date();           

            const  cusIdName = document.getElementById('cusName').value;
       
            fetch('/get_train_calendar', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({'cusIdName': cusIdName, 'interval': interval})
            })
            .then(response => response.json())
            .then(data => {
                if (data['res'] === 'ok') {                    
                    const sex = data['data'][0][1];
                    // 统计每天的训练次数和内容
                    const dateCounts = {};
                    data['data'].forEach(item => {
                        const dateStr = dateToStringGmt(item[3], 'date');
                        if (!dateCounts[dateStr]) {
                            dateCounts[dateStr] = {
                                count: 1,
                                content: item[4]
                            };
                        } else {
                            dateCounts[dateStr].count++;
                        }
                    });
             
                    const result = [];
                    let currentDate = new Date(startDate);
                    while (currentDate <= endDate) {
                        const dateStr = toBeijingTimeString(currentDate);
                        const dateData = dateCounts[dateStr];
                        const isSpot = !!dateData;
                        let content = isSpot ? dateData.content : ':-o';
                        if (isSpot && dateData.count >= 2) {
                            content += ` x${dateData.count}`;
                        }
                        result.push([dateStr, isSpot ? 1 : 0, content]);
                        currentDate.setDate(currentDate.getDate() + 1);
                    }
                    // console.log(result);
                    calendarSpot(result, startDate, endDate, sex);
                    

                } else {
                    const trainCalendar=document.getElementById('trainCalendar');
                    trainCalendar.innerHTML = ' ';
                }
            })
            .catch(error => {
                console.error('获取既往上课错误：', error);
            });
        }

        function calendarSpot(data, startDate, endDate, sex) {
            // console.log(data)
            const trainCalendar=document.getElementById('trainCalendar');
           
            const cusName = document.getElementById('cusName').value.slice(7);
            const interval = 30;
            let titleStr;

            const titleDiv=document.createElement('div');
            titleDiv.id='title'
            titleDiv.innerHTML=`最近运动打卡记录`;
            titleDiv.classList.add('body-report-title');
            titleDiv.style.marginBottom='10px';
            trainCalendar.appendChild(titleDiv);

            let daysCount=0;
            data.forEach(item=>{                
                if(parseInt(item[1])===1){
                    daysCount+=1;
                }
            });

            const txtDiv=document.createElement('div');
            txtDiv.style.textAlign='center';
            txtDiv.id='txt'
            txtDiv.innerHTML=`<span style='font-size:12px;'>最近${interval}天里，你一共运动打卡${daysCount}天。</span>`;
            trainCalendar.appendChild(txtDiv);


            const mainContainer = document.createElement('div');

            mainContainer.id='sportChart';
            trainCalendar.appendChild(mainContainer);
            
            
            const containerWidth = mainContainer.offsetWidth;
            mainContainer.style.width=containerWidth+'px';
            
            const numDays = 7;
            let numWeeks;
            if(interval==='this_year'){
                // numWeeks=52
                const oneDay = 24 * 60 * 60 * 1000;
                const diffDays = Math.round(Math.abs((endDate - startDate) / oneDay));
                numWeeks = Math.ceil(diffDays / 7);
            }else{
                const oneDay = 24 * 60 * 60 * 1000;
                const diffDays = Math.round(Math.abs((endDate - startDate) / oneDay));
                numWeeks = Math.ceil(diffDays / 7);
            }            

            const cellSize = Math.floor(containerWidth / numDays);
            mainContainer.style.height = (cellSize*0.8 * numWeeks)+80 + 'px';
            

            // console.log(numWeeks,cellSize,mainContainer.style.width,mainContainer.style.height)

            const processedData = data.map(item => [item[0], item[1]]);

            myChart = echarts.init(mainContainer);
            // startDate.setDate(startDate.getDate()+1);
            const option = {
                title: {
                    show:false,
                    top: 0,
                    left: 'center',
                    text: titleStr
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        const originalItem = data.find(item => item[0] === params.data[0]);
                        return originalItem ? originalItem[2] : '';
                    }
                },
                visualMap: {
                    show: false,
                    min: 0,
                    max: 1,
                    type: 'piecewise',
                    orient: 'horizontal',
                    left: 'center',
                    top: 65,
                    inRange: {
                        color: ['#fcfaf2', '#f5c647']
                    }
                },
                calendar: {
                    orient: 'vertical',
                    top: 40,
                    left: 40,
                    right: 20,
                    cellSize: [cellSize, cellSize*0.8],
                    range: [toBeijingTimeString(startDate), toBeijingTimeString(endDate)],
                    itemStyle: {
                        borderWidth: 0.5
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#ccc',
                            type: 'solid'
                        }
                    },
                    dayLabel: {
                        firstDay: 1,
                        nameMap: 'cn',
                        margin:8,
                        fontSize: 13,
                        color:'#7d7972'
                    },
                    monthLabel: {
                        show: true,
                        nameMap: 'cn',
                        margin: 15,
                        fontSize: 16,
                        color:'#7d7972'
                    },
                    yearLabel: {
                        show: false
                    }
                },
                series: {
                    type: 'heatmap',
                    coordinateSystem: 'calendar',
                    data: processedData,
                    label: {
                        show: true,
                        formatter: function(p) {
                            return echarts.format.formatTime('d', p.data[0]);
                        },
                        textStyle: {
                            color: '#555555'
                        }
                    }
                }
            };

            myChart.setOption(option);
            
        }

        function showInsSig(){
            const insSig=document.getElementById('insSig');
            insSig.innerHTML='';
            insSig.innerHTML=`
            <div style='display:flex;flex-flow:row;justify-content:start;align-items: baseline;margin-top:20px;'>
                <div style='color:#bfbcb6;font-size:12px;'>鹿鹿泽健身工作室&nbsp;&nbsp;&nbsp;</div>
                <div style='color:#fca903;font-size:16px;'> ${insSigTxt}</div>
                <div style='color:#bfbcb6;font-size:8px;'>&nbsp;&nbsp; 教练</div>
            </div>
            `
        }

        function getCusTrainData(){
            const trainData=document.getElementById('trainData');
            trainData.innerHTML='';
            const title=document.getElementById('title');
            const nameReport=document.getElementById('cusNameReport');
            //清空bodyData下所有子div的内容
            const childDivUnderTrainData=trainData.getElementsByTagName('div');
            for(let i=0;i<childDivUnderTrainData.length;i++){
                childDivUnderTrainData[i].display='none';
            }
            const errInfoTrain=document.getElementById('errInfoTrain');

            errInfoTrain.textContent='';
            trainData.style.display='none';
            const cusIdName=document.getElementById('cusName').value;
            fetch('/get_cus_report_train',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify({'cus_name_id':cusIdName})
                })
                .then(response => response.json())
                .then(data => {
                    // console.log('train data:',data)
                    if(data['res']==='ok'){
                        const res=data['result']
                        if(res['train_date_min']){
                            trainData.style.display='block';
                            const reportDate=document.getElementById('reportDate'); 
                            reportDate.innerHTML=`<div><span style='font-size:12px;color:#828181;'>报告日期: </span><span style='font-size:14px;color:#828181;'>${dateToString(new Date(),'dateChn')}</span></div>`
                            reportDate.style.margin='0px 0px 30px 0px';
                
                            const sexTitle=res['sex']==='女'?'女士':'先生'
                            nameReport.innerHTML=`<div style='display:flex;flex-direction:row;align-items:baseline;justify-content:center;border-radius:12px;width:150px;
                                                    height:30px;font-size:22px;background-color:#fffbf0;color:#f5a442;padding-top:5px;padding-bottom:15px;margin-bottom:20px;margin-left:20px;'>
                                           
                                                    <span style="font-weight:bold;font-size:28px;color:#f7b052;">&nbsp;${document.getElementById('cusName').value.trim().substring(7)}&nbsp;</span>
                                                    <span style='font-size:10px;color:#c2b48f;'>&nbsp;&nbsp;${sexTitle}</span>
                                                    </div>`
                          
                            //p3_1：有氧训练文本，
                            let p3_1='';
                            if(parseFloat(res['total_oxy_time'])>0){
                                p3_1=`<span>${res['total_oxy_time']}</span>分钟的有氧训练<span>`;
                            }else{
                                p3_1='';
                            }

                            //p3_2：其他训练文本
                            let p3_2='';
                            if(res['other_train']){
                                res['other_train'].forEach(item=>{
                                    p3_2=p3_2+item[1]+'次'+item[0]+'课程，'
                                });
                                p3_2=p3_2.trim();
                                if(parseFloat(res['total_oxy_time'])>0){
                                    p3_2='，'+p3_2.slice(0,-1);
                                }else{
                                    p3_2=p3_2.slice(0,-1);
                                }
                                
                                p3_2=`<span>${p3_2}</span>`
                            }else{
                                p3_2=''
                            }

                            //p3_2_1：小团课训练文本
                            let p3_2_1='';
                            if(res['total_group_train_times']!==0){                            
                                p3_2_1=`<span>${res['total_group_train_times']}次，共${res['total_group_time']}分钟的小团课（包含了有氧/肌肉）综合训练</span>`;                             
                            }else{
                                p3_2_1=''
                            }

                            //p3_3：肌肉训练文本
                            let p3_3='';
                            if(parseFloat(res['total_muscle_days'])>0){
                                if(parseFloat(res['total_oxy_time'])>0 || res['other_train']) {
                                    p3_3=`和<span>${res['total_muscle_days']}</span>次肌肉训练`
                                }else{
                                    p3_3=`<span>${res['total_muscle_days']}</span>次肌肉训练`
                                }                               
                               
                            }else{
                                p3_3=''
                            }

                            //p4_1：肌肉训练具体内容文本
                           let p4_1='';
                            if(parseFloat(res['total_muscle_days'])>0){
                                res['non_oxy_train_by_muscle'].forEach(item=>{
                                    p4_1=p4_1+item[1]+'组'+item[0]+'、'
                                });
                                p4_1=p4_1.trim();
                                p4_1='包含了'+p4_1.slice(0,-1)
                                p4_1=`<p>· 在这${res['total_muscle_days']}</span>次肌肉训练中，${p4_1}的锻炼。</p>`
                            }else{
                                p4_1='';
                            }

                            //p5_1：按周计算文本
                            let p5_1='';
                            if(parseFloat(res['oxy_time_per_week'])===0 && parseFloat(res['muscle_days_per_week'])===0){
                                p5_1=''
                            }else{
                                p5_1=`<p>· 如果按周来算，你平均每周完成<span>${(parseFloat(res['oxy_time_per_week'])/60).toFixed(1)}</span>小时的有氧训练，
                                        <span>${(parseFloat(res['muscle_days_per_week'])).toFixed(1)}</span>天的肌肉训练。</p>`
                            }

                            
                            const trainText=document.createElement('div');
                            trainText.innerHTML=`
                                <div id='reportBox' class='report-box'>
                                    <div >
                                        <p>· ${dateToStringGmt(res['train_date_min'],'dateChn')}，你在鹿鹿泽健身上了第一节课。</p>
                                        <p>· 在这<span>${res['total_club_days']}</span>天里，你在鹿鹿泽健身共完成了<span>${res['total_train_times']}次训练。</span></p>
                                        <p>· 其中包括了`+p3_1+p3_2+p3_2_1+p3_3+`。</p>`+
                                        p4_1+
                                        p5_1+
                                    `</div>
                                </div>
                                <div style='font-size:10px;margin:10px;padding:10px;text-indent:2em;'>中国人群身体活动指南（2021）
                                    建议：18-64岁的成年人，每周累计进行2.5~5小时中等强度有氧活动，或75~150分钟高强度有氧活动，
                                    或等量的中等强度和高强度有氧活动组合。每周至少进行两天肌肉力量练习。
                                </div>
                                `
                            trainData.appendChild(trainText);
                        }else{
                            const errInfoTrain=document.getElementById('errInfoTrain');
                            errInfoTrain.textContent='你还没有我们这里开始训练呢'
                        }
                        
                
                    }
                    
                    
                })
                .catch(error => console.error('Error:', error));


            }

        function pickAfterBodyProblemTxt(pos){       
            const randomIndex = Math.floor(Math.random() * pageTxtLib['res']['show_body_data.html'][pos].length); // 生成一个 0 到数组长度减一的随机整数

            const randomTxt = pageTxtLib['res']['show_body_data.html'][pos][randomIndex]; // 获取随机索引对应的元素


            return randomTxt; // 输出随机获取的元素
        }

        function getCusReportBodyData(){

            const bodyData=document.getElementById('bodyData');
            //清空bodyData下所有子div的内容
            const childDivUnderBodyData=bodyData.getElementsByTagName('div');
            for(let i=0;i<childDivUnderBodyData.length;i++){
                childDivUnderBodyData[i].display='none';
            }
            const errInfo=document.getElementById('errInfo');

            errInfo.textContent='';
            bodyData.style.display='none';
            const cusIdName=document.getElementById('cusName').value;
            fetch('/get_cus_report_body', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify({'cus_name_id':cusIdName})
                })
                .then(response => response.json())
                .then(data => {
                // console.log('get cus report data:',data['res'],data['result']);
                if(data['res']==='ok'){
                    bodyData.style.display='block';
                    for(let i=0;i<childDivUnderBodyData.length;i++){
                        childDivUnderBodyData[i].display='block';
                    }

                    //比较最近一次体验日与今天的天数，如果大于5天，语句有所不同
                    const today=new Date('');
                    const daysDiff=compareDatesDiffDays(dateToStringGmt(data['result']['fiveItems'][0],'date'),dateToString(today,'date'));
    

                    let afterBodyProblemTxt='';
                    if(daysDiff>5){
                        afterBodyProblemTxt=pickAfterBodyProblemTxt('p_1');
                    }else{
                        afterBodyProblemTxt=pickAfterBodyProblemTxt('p_2');
                    }

                    let latestBodyProblemHtml='';
                    const latestBodyProblemData=data['result']['latest5MsrData']['body_problems'][data['result']['latest5MsrData']['body_problems'].length-1];
                    if(latestBodyProblemData!=='-'){
                        latestBodyProblemHtml=
                        `<div style='display:flex;flex-flow:column;align-items:start;
                                            justify-content:start;margin:18px;padding:10px;
                                            font-size:12px;border-radius:4px;border:1px solid #f5a442;'>
                            <p style='margin:4px;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在这次体测中，我发现你有以下情况需要认真关注及调整：</p>
                            <p style='margin:4px;color:#2056ab;font-weight:bold;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${latestBodyProblemData}</p>
                            <p style='margin:4px;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${afterBodyProblemTxt}</p>
                        </div>
                        `

                    }
                    
                    const bodyTitle=document.getElementById('bodyTitle');
                    bodyTitle.innerHTML=`<div style='display:flex;align-items:center;
                                            justify-content:center;margin-bottom:30px;
                                            padding-left:5px;padding-right:5px;
                                            padding-top:3px;padding-bottom:3px;
                                            height:30px;border-radius:4px;
                                            width:98%;
                                            background-color:#f5a442;color:#FFFFFF;font-size:14px;'>
                                            你最近一次体测的日期是 ${dateToStringGmt(data['result']['fiveItems'][0],'dateChn')}
                                            </div> `+
                                            latestBodyProblemHtml+
                                            `<div style='margin-top:30px;margin-bottom:30px;margin-left:6px;margin-right:6px;font-size:14px;color:#939596;'>
                                            以下是你这次体测的重要指标：
                                            </div>`;

                    const totalMsrTimes=data['result']['total_msr_times'];
                    const latestMsrTimes=data['result']['latest5MsrData']['msr_date'].length;
                    const changeTitle=document.getElementById('changeTitle');
                    // console.log(totalMsrTimes)
                    let changeTitlePost,wtTitle,waistTitle,hipTitle,chestTitle,legTitle,armTitle;
                    if(totalMsrTimes===1){
                        changeTitlePost='看看这次的体测其他结果吧';
                        wtTitle='体重(Kg)';
                        chestTitle='胸围(cm)变化';
                        waistTitle='腰围(cm)变化';
                        hipTitle='臀围(cm)变化';
                        legTitle='腿围(cm)变化';
                        armTitle='臂围(cm)变化';

                    }else{
                        changeTitlePost=`看看最近${latestMsrTimes}次的变化吧。`;
                        wtTitle='体重(Kg)变化';
                        chestTitle='胸围(cm)变化';
                        waistTitle='腰围(cm)变化';
                        hipTitle='臀围(cm)变化';
                        legTitle='腿围(cm)变化';
                        armTitle='臂围(cm)变化';
                    }


                    changeTitle.innerHTML=`<div style='display:flex;flex-flow:column;align-items:center;
                                            justify-content:center;margin-bottom:30px;
                                            border-radius:4px;
                                            background-color:#f5a442;color:#FFFFFF;font-size:14px;padding-left:5px;padding-right:5px;
                                            padding-top:3px;padding-bottom:3px;'>
                                            <div>你在鹿鹿泽健身一共体测了${totalMsrTimes}次</div><div>`+changeTitlePost+
                                            `</div></div> `
                    showBfr(data['result']['bfr_bmi']);
                    showBmi(data['result']['bfr_bmi'][7]);
                    showFiveItems(data['result']['fiveItems'])
                    showChange([data['result']['latest5MsrData']['msr_date'],data['result']['latest5MsrData']['wt']],
                                'wtChange',
                                wtTitle,
                                yRangeRes(data['result']['latest5MsrData']['wt']),
                                '#f5a442',
                                '#f5f5f2');
                    showChange([data['result']['latest5MsrData']['msr_date'],data['result']['latest5MsrData']['chest']],
                                'chestChange',
                                chestTitle,
                                yRangeRes(data['result']['latest5MsrData']['chest']),
                                '#f5a442',
                                '#f5f5f2');
                    showChange([data['result']['latest5MsrData']['msr_date'],data['result']['latest5MsrData']['waist']],
                                'waistChange',
                                waistTitle,
                                yRangeRes(data['result']['latest5MsrData']['waist']),
                                '#f5a442',
                                '#f5f5f2');
                    showChange([data['result']['latest5MsrData']['msr_date'],data['result']['latest5MsrData']['hip']],
                                'hipChange',
                                hipTitle,
                                yRangeRes(data['result']['latest5MsrData']['hip']),
                                '#f5a442',
                                '#f5f5f2');
                    showChange2([data['result']['latest5MsrData']['msr_date'],data['result']['latest5MsrData']['l_leg'],data['result']['latest5MsrData']['r_leg']],
                                'legChange',                                
                                legTitle,         
                                ['左大腿围','右大腿围'],                       
                                yRangeRes(data['result']['latest5MsrData']['l_leg']),
                                ['#587bcc','#86cc58'],
                                '#f5f5f2');
                    showChange2([data['result']['latest5MsrData']['msr_date'],data['result']['latest5MsrData']['l_arm'],data['result']['latest5MsrData']['r_arm']],
                                'armChange',                                
                                armTitle,
                                ['左臂围','右臂围'],
                                yRangeRes(data['result']['latest5MsrData']['l_arm']),
                                ['#587bcc','#86cc58'],
                                '#f5f5f2');
                }else{
                    bodyData.style.display='none';
                    errInfo.textContent='你还没有在我们这里做过体测';
                }
                
                
   
                 })
                .catch(error => console.error('Error:', error));
        }

        function showChange(data,id,title,yRange,color,bgColor){
            let dateStr=[];
            data[0].forEach(date=>{
                dateStr.push(dateToStringGmt(date,'date'))
            })
            const chartContainer=document.getElementById(id);
            const myChart = echarts.init(chartContainer);
            

            // 定义图表的配置项和数据
            const options  = {
                // grid: {
                //     left: '50px',
                //     right: '50px',
                //     top: '50px',
                //     bottom: '50px'
                // },
                color:color,
                backgroundColor:bgColor,
                title: {
                    text: title,
                    left:15,
                    top:5,
                    textStyle:{
                        color: '#c9bdb5',
                    }
                },
                tooltip: {},
                xAxis: {
                    
                    data: dateStr
                },
                yAxis: {
                    min:yRange[0],
                    max:yRange[1],
                },
                series: [{
                    name: title,
                    type: 'line',
                    data: data[1],
                    label:{
                        show:true,
                        position:'top',
                    },
                    itemStyle: {
                        borderRadius: 10  // 设置圆角半径
                    }
                    
                }]
            };

            // 使用刚指定的配置项和数据显示图表
            myChart.setOption(options);

        }

        function showChange2(data,id,title,names,yRange,colors,bgColor){
            let dateStr=[];
            data[0].forEach(date=>{
                dateStr.push(dateToStringGmt(date,'date'))
            })
            const chartContainer=document.getElementById(id);
            const myChart = echarts.init(chartContainer);
            

            // 定义图表的配置项和数据
            const options  = {
                // grid: {
                //     left: '50px',
                //     right: '50px',
                //     top: '50px',
                //     bottom: '50px'
                // },
                color:colors,
                backgroundColor:bgColor,
                title: {
                    text: title,
                    left:15,
                    top:5,
                    textStyle:{
                        color: '#c9bdb5',
                    }
                },
                legend: {
                    data: names,  // 图例的名称，与series中的name对应
                    show: true,
                    top: '10%'  // 调整图例的位置
                },
                tooltip: {},
                xAxis: {                    
                    data: dateStr
                },
                yAxis: {
                    min:yRange[0],
                    max:yRange[1],
                },
                series: [{
                    name: names[0],
                    type: 'line',
                    data: data[1],
                    label:{
                        show:true,
                        position:'top',
                        distance:6,
                        color:colors[0]
                    },
                    itemStyle: {
                        borderRadius: 10  // 设置圆角半径
                    }
                },
                {
                    name: names[1],
                    type: 'line',
                    data: data[2],
                    label:{
                        show:true,
                        position:'top',
                        distance:18,
                        color:colors[1]
                    },
                    itemStyle: {
                        borderRadius: 10  // 设置圆角半径
                    }
                    
                }]
            };

            // 使用刚指定的配置项和数据显示图表
            myChart.setOption(options);

        }


        function showBfr(bfrData){
            // const bfrData=[0.10,0.16,0.21,0.26,0.45,0.18]
            const bfr=bfrData[6]
            const percent_bfr=(parseFloat(bfr)*100-5)/40
            let bfrTxt;
            if(bfr<bfrData[0]){              
                bfrTxt='你的体脂率是 '+(parseFloat(bfr)*100).toFixed(2)+'%，\n有点低了。'
            }
            if(bfr>=bfrData[0] && bfr<=bfrData[2]){
                bfrTxt='你的体脂率是 '+(parseFloat(bfr)*100).toFixed(2)+'%，\n不错哟。'
            }
            if(bfr>bfrData[2] && bfr<=bfrData[3]){
                bfrTxt='你的体脂率是 '+(parseFloat(bfr)*100).toFixed(2)+'%，\n有肉肉了哦。'
            }
            if(bfr>=bfrData[3]){
                bfrTxt='你的体脂率是 '+(parseFloat(bfr)*100).toFixed(2)+'%，\n要认真对待哟！'
            }
    
            const chartContainer = document.getElementById('bfr');
            
            // 初始化图表
            const chart = echarts.init(chartContainer);

            // 配置图表选项
            const option = {
            title: {
                    text: '估算体脂率',
                    textStyle:{
                        color: '#c9bdb5',
                    },
                },
            xAxis: {
                type: 'value',
                show:false,
                min:5,
                max: 45, // x轴最大值
                position: 'top', // x轴位置在上方
            },
            yAxis: {
                type: 'category',
                show:false,
                data: [''], // y轴数据为空，只是为了占位
            },
            series: [
                {
                    name:'bfr',
                    type: 'bar',
                    data: [45], // 条形图的数据
                    itemStyle: {
                        // color: '#ffafad', // 条形图颜色
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#fff1d4' }, // 渐变起始颜色
                        { offset: 1, color: '#ffce6b' }, // 渐变结束颜色
                        ]),
                    },
                    markLine:{
                        lineStyle: {
                            type: 'dashed', // 设置线条样式为实线
                        },
                        symbol:['none','none'],
                        itemStyle:{
                            normal:{
                                color:'#FA8565',
                                label:{
                                    show:false
                                }
                            }
                        },
                        data:[
                            {
                                xAxis:parseFloat(bfrData[0])*100,
                                // xAxis:21,
                                silent:true,
                            },
                            // {
                            //     xAxis:parseFloat(bfrData[1])*100,
                            //     silent:true,
                            // },
                            {
                                xAxis:parseFloat(bfrData[2])*100,
                                // xAxis:35,
                                silent:true,
                            },
                            // {
                            //     xAxis:parseFloat(bfrData[3])*100,
                            //     silent:true,
                            // },
                            //测量的bfr
                            {
                                xAxis:parseFloat(bfrData[6])*100,
                                silent:true,
                                itemStyle:{
                                    color:'#94570d',
                                },
                                lineStyle:{
                                    type:'solid',
                                    width:2,
                                }
                            },
                        ]
                    }
                },
        
            ],
            graphic: [
                {
                    type: 'text',
                    left: (parseFloat(bfrData[0])*100-5)*100*0.88/40+'%', // 标记文本距离左边的位置
                    top: '66%', // 标记文本距离上边的位置
                    style: {
                        text: parseFloat(bfrData[0])*100+'%',
                        fill: '#FA8565',
                    },
                },
                // {
                //     type: 'text',
                //     left: (parseFloat(bfrData[1])*100-5)*100/35+'%', // 标记文本距离左边的位置
                //     top: '66%', // 标记文本距离上边的位置
                //     style: {
                //         text: data[1]*100+'%',
                //         fill: '#FA8565',
                //     },
                // },
                {
                    type: 'text',
                    left: (parseFloat(bfrData[2])*100-5)*100*0.88/40+'%', // 标记文本距离左边的位置
                    top: '66%', // 标记文本距离上边的位置
                    style: {
                        text:  parseFloat(bfrData[2])*100+'%',
                        fill: '#FA8565',
                    },
                },
                {
                    type: 'text',
                    left: percent_bfr*100*0.75+'%',
                    top: '12%',
                    style: {
                        text: bfrTxt,
                        fill: '#94570d',
                    },
                },
            ],
            };

            // 渲染图表
            chart.setOption(option);

        }

        function showBmi(bmi){
        
            const chartContainer = document.getElementById('bmi');
            if(bmi<18.5){
                if(bmi<15){
                    bmi=15
                }                
                bmiTxt='你的BMI是 '+bmi+'，\n有点瘦了。'
            }
            if(bmi>=18.5 && bmi<=24){
                bmiTxt='你的BMI是 '+bmi+'，\n继续保持哦。'
            }
            if(bmi>24 && bmi<28){
                bmiTxt='你的BMI是 '+bmi+'，\n有点重哦！'
            }
            if(bmi>=28){
                bmiTxt='你的BMI是 '+bmi+'，\n胖了，\n需要认真减脂了！'
            }

            percent_bmi=(bmi-15)/20

            // 初始化图表
            const chart = echarts.init(chartContainer);

            // 配置图表选项
            const option = {
            title: {
                    text: 'BMI',
                    textStyle:{
                        color: '#c9bdb5',
                    },
                },
            xAxis: {
                type: 'value',
                show:false,
                min:15,
                max: 35, // x轴最大值
                position: 'top', // x轴位置在上方
            },
            yAxis: {
                type: 'category',
                show:false,
                data: [''], // y轴数据为空，只是为了占位
            },
            series: [
                {
                    name:'bmi',
                    type: 'bar',
                    data: [40], // 条形图的数据
                    itemStyle: {
                        // color: '#ffafad', // 条形图颜色
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#ffcfcf' }, // 渐变起始颜色
                        { offset: 1, color: '#ff9896' }, // 渐变结束颜色
                        ]),
                    },
                    markLine:{
                        lineStyle: {
                            type: 'dashed', // 设置线条样式为实线
                        },
                        symbol:['none','none'],
                        itemStyle:{
                            normal:{
                                color:'#f78a05',
                                label:{
                                    show:false
                                }
                            }
                        },
                        data:[
                            {
                            xAxis:18.5,
                            silent:true,
                            },
                            {
                            xAxis:24,
                            silent:true,
                            },
                            {
                            xAxis:28,
                            silent:true,
                            },
                            {
                            xAxis:28,
                            silent:true,
                            },
                            {
                            xAxis:bmi,
                            silent:true,
                            itemStyle:{
                                color:'#ad66a7',
                            },
                            lineStyle:{
                                type:'solid',
                                width:2,
                            }
                            },
                        ]
                    }
                },
           
            ],
            graphic: [
                {
                    type: 'text',
                    left: '17.5%', // 标记文本距离左边的位置
                    top: '65%', // 标记文本距离上边的位置
                    style: {
                        text: '18.5',
                        fill: '#FA8565',
                    },
                },
                {
                    type: 'text',
                    left: '45%',
                    top: '65%',
                    style: {
                        text: '24',
                        fill: '#FA8565',
                    },
                },
                {
                    type: 'text',
                    left: '62%',
                    top: '65%',
                    style: {
                        text: '28',
                        fill: '#FA8565',
                    },
                },
                {
                    type: 'text',
                    left: percent_bmi*100*0.75+'%',
                    top: '12%',
                    style: {
                        text: bmiTxt,
                        fill: '#ad66a7',
                    },
                },
            ],
            };

            // 渲染图表
            chart.setOption(option);

        }

        function showFiveItems(data){
            //data的顺序：msr_date,balance,core,flex,heart,power
            // 获取DOM元素
            const chartContainer = document.getElementById('radarBox');

            // 基于Echarts创建实例
            const chart = echarts.init(chartContainer);

            // 配置雷达图的数据和选项
            const options = {
                title: {
                    text: '身体素质',
                    textStyle:{
                        color: '#c9bdb5',
                    },
                },
                tooltip: {},
                radar: {
                    indicator: [
                    { name: '心肺', max: 10 },
                    { name: '平衡', max: 10 },
                    { name: '力量', max: 10 },
                    { name: '柔韧性', max: 10 },
                    { name: '核心', max: 10 }
                    ]
                },
                series: [{
                    type: 'radar',
                    data: [
                    {
                        value: [data[4],data[1],data[5],data[3],data[2]],
                        name: dateToStringGmt(data[0],'date'),
                        lineStyle:{
                            color: '#fab9f4',
                        },
                        itemStyle:{
                            color: '#fab9f4',
                        },
                        areaStyle: {
                            color: 'rgba(255, 222, 252, 0.8)', // 填充颜色及透明度
                        },
                    },
                    
                    ]
                }]
            };


            // 使用配置项生成雷达图
            chart.setOption(options);

        }

        function generateIndOcc(ind_occ_data){
            const indSel=document.getElementById('industrySelect');
            const occSel=document.getElementById('occuSelect');

            const indData=ind_occ_data['industries'];
            const occData=ind_occ_data['occus'];

            indData.forEach(ind=>{
                const indOpt=document.createElement('option');
                indOpt.value=ind[0];
                indOpt.text=ind[1];
                indSel.appendChild(indOpt);
            });

            occData.forEach(occ=>{
                const occOpt=document.createElement('option');
                occOpt.value=occ[0];
                occOpt.text=occ[1];
                occSel.appendChild(occOpt);
            });

            indSel.addEventListener('change',function(){
                //如果是学生，则职业不给选，强制为“学生”
                if(indSel.value==='INT010'){
                    occSel.value='OCC03';
                    occSel.disabled=true;
                }else{
                    occSel.value='OCC01';
                    occSel.disabled=false;
                }        
            });

        }

        function handleCusNameInput() {
            
            // 获取输入框中的值
            const cusName=document.getElementById("cusName");
            const searchTerm = document.getElementById("cusName").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            const resultList=document.getElementById('cusNameList')
            const rptBox=document.getElementById('reportBox');
            rptBox.style.display='none';

            cusName.addEventListener("click", function(event) {
                event.stopPropagation();
            });

            // 清空列表
            resultList.style.display = "block";
            resultList.innerHTML = "";
            
            // if (UpperSearchTerm === "") {
            //     // resultList.style.display = "none";
            //     resultList.style.display = "block";
            //     return; // 输入框为空，不做处理
            // }else{
            //     resultList.style.display = "block";

            // }

           
            
            // 遍历给定的数组，进行模糊匹配。倒序
            cusList.reverse().forEach(function(item) {
           
                if (item.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = item;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function(event) {                        
                        event.stopPropagation();
                        const reportBox=document.getElementById('reportBox');
                        reportBox.style.display='none';
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusName").value = item;  

                        resultList.style.display = "none";

                        resultList.innerHTML = "";

                        generateInsNickName();
                        showReport();
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                    resultList.classList.add('cus-list-result-show');
                }
            });
        
            
        }



    </script>
  
</body>
</html>
